import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [

  {
    path: '/index',
    name: 'index',
    meta:{title:'首页'},
    component: () => import('../views/Index.vue'),
    children:[
      {
        path: '/index/home',
        name: 'home',
        meta:{title:'首页'},
        component: () => import('../views/index/Home.vue'),
      },
      {
        path: '/index/tuan',
        name: 'tuan',
        meta:{title:'爆爆团'},
        component: () => import('../views/index/Tuan.vue'),
      },
      {
        path: '/index/order',
        name: 'order',
        meta:{title:'订单'},
        component: () => import('../views/index/Order.vue'),
      },
      {
        path: '/index/mine',
        name: 'mine',
        meta:{title:'我的'},
        component: () => import('../views/index/Mine.vue'),
      },
      // 重定向
      {
        path: '/index',
        redirect:"/index/home"
      },
      // 404
      {
        path:'*',
        component: () => import('../views/NotFound.vue'),
      }
    ]
  },

  {
    path: '/detail/:id',
    name: 'detail',
    meta:{title:'详情'},
    component: () => import('../views/Details.vue'),
  },
  {
    path: '/collection',
    name: 'collection',
    meta:{title:'收藏'},
    component: () => import('../views/Collection.vue'),
  },
  {
    path: '/login',
    name: 'login',
    meta:{title:'登录'},
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/regist',
    name: 'regist',
    meta:{title:'注册'},
    component: () => import('../views/Regist.vue'),
  },
  {
    path: '/searchview',
    name: 'searchview',
    meta:{title:'搜索'},
    component: () => import('../views/SearchView.vue'),
    children:[
      {
        path: '/searchview/index',
        name: 'searchviewindex',
        meta:{title:'搜索'},
        component: () => import('../views/search/SearchIndex.vue'),
      },
      {
        path: '/searchview/list',
        name: 'searchviewlist',
        meta:{title:'搜索'},
        component: () => import('../views/search/SearchResults.vue'),
      },
      // 重定向
      {
        path: '/searchview',
        redirect:"/searchview/index"
      },
      // 404
      {
        path:'*',
        component: () => import('../views/NotFound.vue'),
      }
    ]
  },
  // 重定向
  {
    path: '/',
    redirect:'/index'
  },
  // 404
  {
    path:'*',
    meta:{title:'404'},
    component: () => import('../views/NotFound.vue'),
  }
]


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to,feom,next)=>{

  // 动态更新网页标题
  document.title = to.meta && to.meta.title
  
  //获取localStorage中的登陆凭证
  const token = localStorage.getItem('token');

  if(to.path == "/index/order" || to.path == "/index/mine"){
    if( token ){
      next()
    }else{
      Toast('该页面登录后才能访问')
      next('/login')
    }
  }else{
    next()
  }
})

export default router
